<template>
  <div id='Roles'>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      </el-row>
      <el-table :data="rolusList" border stripe>
        <!-- 列开项 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['dnbottom', i1 === 0 ? 'dbtop' : '']" v-for="(item1, i1) in scope.row.children"
              :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="3">
                <el-tag closable @close="removeRolesById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级,三级权限 -->
              <el-col :span="21">
                <el-row :class="['dnbottom', i2 === 0 ? 'dbtop' : '']" v-for="(item2, i2) in item1.children"
                  :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRolesById(scope.row, item2.id)">{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable
                      @close="removeRolesById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :hide-after="2000" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="editRoles(scope.row.id)">编辑</el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :hide-after="2000" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="delRolesList(scope.row.id)">删除
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :hide-after="2000" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="small" @click="assignRoles(scope.row)">分配权限
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户弹出框区域 -->
    <el-dialog title="添加用户角色" :visible.sync="addDialogVisible" width="30%" @close="clearAdd">
      <el-form ref="addRolesForm" :model="addRolesFormList" :rules="RolesRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesFormList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesFormList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息区域 -->
    <el-dialog title="编辑用户角色" :visible.sync="editDialogVisible" width="30%">
      <el-form ref="editRolesForm" :model="editRolusList" :rules="RolesRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input :value="editRolusList.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolusList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分配权限区域 -->
    <el-dialog title="编辑角色权限" :visible.sync="assignDialogVisible" width="30%" @close="setTreeListById">
      <el-tree :data="assignRolesList" accordion :props="assignRolesProps" show-checkbox node-key="id"
        :default-checked-keys="treeListById" ref="treeRef" default-expand-all></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getRolesListById">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  created() {
    this.getRolesList()
  },
  data() {
    return {
      getRolesListId: '',
      rolusList: [],
      editRolusList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addRolesFormList: {
        roleName: '',
        roleDesc: ''
      },
      assignRolesList: [],
      assignDialogVisible: false,
      assignRolesProps: {
        children: 'children',
        label: 'authName'
      },
      treeListById: [],
      // 用户表单确认规则区域
      RolesRules: {
        roleName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, message: '长度应在 3 个字符以上', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取用户角色数据
    async getRolesList() {
      const { data, meta } = await this.$http.get('roles')
      if (meta.status !== 200) return this.$message.error('角色列表数据获取失败')
      this.rolusList = data
    },
    // 添加用户的确定操作
    confirmAddRoles() {
      this.$refs.addRolesForm.validate(async (valid) => {
        if (!valid) return this.$message.error('表单数据验证失败,请重新输入!')
        const { meta } = await this.$http.post('roles', this.addRolesFormList)
        if (meta.status !== 201) return this.$message.error('角色创建失败,请重新填写')
        this.$message.success('角色创建成功!')
        this.getRolesList()
        this.addDialogVisible = false
      })
    },
    // 关闭表单清空数据
    clearAdd() {
      this.$refs.addRolesForm.resetFields()
    },
    // 删除用户信息
    delRolesList(id) {
      this.$confirm('该角色数据将永久删除, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { meta } = await this.$http.delete(`roles/${id}`)
        if (meta.status !== 200) return this.$message.error('角色数据删除失败')
        this.getRolesList()
        this.$message.success('角色数据删除成功')
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 通过递归形式将三级权限保存到this.treeListById中
    getKeyList(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => this.getKeyList(item, arr))
    },
    // 分配权限设置
    async assignRoles(role) {
      const { data, meta } = await this.$http.get('rights/tree')
      if (meta.status !== 200) return this.$message.error('角色权限获取失败!请稍后再试')
      this.assignRolesList = data
      this.getRolesListId = role.id
      this.getKeyList(role, this.treeListById)
      this.assignDialogVisible = true
    },
    // 编辑用户角色
    async editRoles(id) {
      const { data, meta } = await this.$http.get(`roles/${id}`)
      if (meta.status !== 200) return this.$message.error('角色数据获取失败,请稍后再试')
      this.editRolusList = data
      this.editDialogVisible = true
    },
    // 修改角色描述
    async confirmEditRoles() {
      const { meta } = await this.$http.put(`roles/${this.editRolusList.roleId}`, this.editRolusList)
      if (meta.status !== 200) return this.$message.error(meta.msg)
      this.getRolesList()
      this.$message.success('角色描述修改成功!')
      this.editDialogVisible = false
    },
    // 删除角色权限
    removeRolesById(role, RightId) {
      this.$confirm('此操作将永久删除该角色权限, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message('已取消删除')
      }).then(async () => {
        const { meta, data } = await this.$http.delete(`roles/${role.id}/rights/${RightId}`)
        if (meta.status !== 200) return this.$message.error(meta.msg)
        role.children = data
        this.$message.success(meta.msg)
      })
    },
    setTreeListById() {
      this.treeListById = []
    },
    async getRolesListById() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { meta } = await this.$http.post(`roles/${this.getRolesListId}/rights`, { rids: idStr })
      if (meta.status !== 200) return this.$message.error('角色权限提交失败,请稍后再试')
      this.getRolesList()
      this.$message.success('角色权限更新成功')
      this.getRolesListId = ''
      this.assignDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin: 0 50px;
  padding: 5px 0;
  display: flex;
  align-items: center;
}

/deep/.el-table {
  margin-top: 15px;
}

/deep/.el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  border-bottom: 2px solid #d0d2d7;
}

/deep/.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background: #dbf1fb;
}

/deep/.el-tag {
  margin: 2px 5px;
}

.dbtop {
  border-top: 1px solid #eee;
}

.dnbottom {
  border-bottom: 1px solid #eee;
}
</style>
